#include<bits/stdc++.h>
#define ll long long
using namespace std;
#define B 23
const ll MOD=0xdead3b800001,P=1e9+7;
int n,a[1111],b[1111];
unordered_set<ll> mp;
vector<int> vv;
ll hsh(){
	ll ret=0;for(auto i:vv) ret=(ret*B+i)%MOD;
	return ret;
}
void dfs(int x,int y){
	if(x==n&&y==n) return void(mp.insert(hsh()));
	if(x<n) vv.push_back(b[y]),dfs(x+1,y),vv.pop_back();
	if(y<n) vv.push_back(a[x]),dfs(x,y+1),vv.pop_back();
}
ll qpow(ll x,ll y=P-2){ll z=1;while(y){if(y&1)z=z*x%P;x=x*x%P,y>>=1;}return z;}
int main(){
	freopen("zha.in","r",stdin);
	freopen("zha.out","w",stdout);
	cin.tie(nullptr)->sync_with_stdio(false);
	int i;cin>>n;bool F=1;
	for(i=1;i<=n;i++) cin>>a[i],F&=(a[i]==i);
	for(i=1;i<=n;i++) cin>>b[i];
	if(n<=10){
		dfs(1,1);
		cout<<mp.size()<<'\n';
		return 0;
	}
	if(F){
		if(b[1]==n){
			n--;
			ll ans=1;
			for(i=1;i<=n;i++) ans=ans*i%P;
			ans=qpow(ans);
			for(i=n+1;i<=n+n;i++) ans=ans*i%P;
			cout<<ans<<'\n';
		}
		else{
			n--;
			ll ans=1;
			for(i=1;i<=n;i++) ans=ans*i%P;
			ans=qpow(ans);
			for(i=n+1;i<=n+n;i++) ans=ans*i%P;
			ans=ans*qpow(n+1)%P;
			cout<<ans<<'\n';
		}
		return 0;
	}
	return 0;
}
